<!--
    by: yuanbiao 2021年07月26日
    name: x-star-bar
    notes:
-->
<template>
  <div :class="[
      prefixCls,
      `${prefixCls}-${type}`,
      disabled ? `${prefixCls}-disabled` : ''
    ]"
    @mouseleave="hoverIndex=0"
    @mouseout="hoverIndex=0"
  >
    <i v-for="i in 5" :key="i"
      :class="[
        `${prefixCls}__item`,
        'xvu-iconfont',
        (fill || i <= activeIndex) ? 'xvu-star-fill' : 'xvu-star',
        {
          active: (hoverIndex <= 0) && (i <= activeIndex),
          hover: i <= hoverIndex
        }
      ]"
      :style="styles"
      @click="clickStarHandler(i)"
      @mouseover="mouseoverStarHandler(i)"
    ></i>
  </div>
</template>

<script>
const prefixCls = 'x-star-bar'
export default {
  name: 'x-star-bar',
  props: {
    size: {
      type: [Number, String],
      default: 16
    },
    type: {
      type: String,
      default: 'default'
    },
    index: {
      type: [Number, String],
      default: 0
    },
    fill: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      prefixCls: prefixCls,
      activeIndex: 0,
      hoverIndex: 0,
    }
  },
  computed: {
    styles () {
      return {
        fontSize: `${this.size}px`,
      }
    }
  },
  watch: {
    index: {
      handler (n) {
        if (this.activeIndex === parseInt(n)) return
        this.activeIndex = parseInt(n)
      },
      immediate: true
    }
  },
  methods: {
    clickStarHandler (index) {
      if (this.disabled) return
      this.activeIndex = index
      this.$emit('click', index)
    },
    mouseoverStarHandler (index) {
      if (this.disabled) return
      this.hoverIndex = index
    }
  }
}
</script>
